package com.star.tool.demo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import static android.view.KeyEvent.KEYCODE_BACK;

public class WebViewActivity extends AppCompatActivity {

    private WebView mWebView;

    //视频全屏相关
    private final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private FullscreenHolder mFullscreenHolder;

    private String test_url = "http://video.funeralchain.com/video/8ca889adbf574c0b8cbb1c6afa1d7db3/transcode_1522034715584/66132322-7fbd-4906-8c04-4d6fa6298c5e.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_web_view);
//        mWebView = findViewById(R.id.mWebView);
        initWebView();
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MasWebChromeClient());
        mWebView.loadUrl(test_url);
//        mWebView.loadUrl("file:///android_asset/test.html");//加载assets目录下test.xml


        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                        String mimetype, long contentLength) {
                //1.使用手机浏览器下载
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
                //2.自己控制下载（FileDownLoad等等）
            }
        });
    }

    /**
     * 初始化webView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        //设置支持javascript控件响应
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕（两个配置合用）
        webSettings.setLoadWithOverviewMode(true);  // 缩放至屏幕的大小
        webSettings.setUseWideViewPort(true);       //扩大等比缩放（将图片调整到适合webView的大小）
        //缩放操作
        webSettings.setSupportZoom(false);          //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false);  //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false);  //隐藏原生的缩放控件
        //其他细节操作
        webSettings.setDefaultTextEncodingName("utf-8");               //设置编码格式
        webSettings.setAllowFileAccess(true);                          //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);    //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true);                 //支持自动加载图片
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把所有内容放大WebView等宽的一列中（支持内容重新布局）
        //http/https混合加载
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//api21
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //允许自动播放多媒体
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {//api17
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        //硬件加速（有bug-如果导致花屏就关闭）（在application或所在activity开启==》android:hardwareAccelerated="true"）
//        android:configChanges="orientation|screenSize|keyboardHidden"
    }

    /**
     * MasWebChromeClient（支持视频播放全屏）
     * android:configChanges="orientation|screenSize|keyboardHidden"
     */
    private class MasWebChromeClient extends WebChromeClient {
        private View mCustomView;
        private CustomViewCallback mCustomViewCallback;

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            WebViewActivity.this.getWindow().getDecorView();
            FrameLayout decor = (FrameLayout) getWindow().getDecorView();
            mFullscreenHolder = new FullscreenHolder(WebViewActivity.this);
            mFullscreenHolder.addView(view, COVER_SCREEN_PARAMS);
            decor.addView(mFullscreenHolder, COVER_SCREEN_PARAMS);
            mCustomView = view;
            mCustomViewCallback = callback;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        public void onHideCustomView() {
            if (mCustomView == null) {
                return;
            }
            FrameLayout decor = (FrameLayout) getWindow().getDecorView();
            decor.removeView(mFullscreenHolder);
            mFullscreenHolder = null;
            mCustomView = null;
            mCustomViewCallback.onCustomViewHidden();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            super.onHideCustomView();
        }
    }

    /**
     * 设置WebView生命周期
     */
    @Override
    protected void onResume() {
        //激活，正常执行网页响应
        mWebView.onResume();
        //恢复pauseTimers状态
//        mWebView.resumeTimers();
        super.onResume();
    }

    @Override
    protected void onPause() {
        //通知内核暂停所有的动作（DOM解析、plugin执行、javascript执行）
        mWebView.onPause();
        //针对全局的webView，暂停所有webView的layout、parsing、javascripttimer，降低cpu功耗
//        mWebView.pauseTimers();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        //销毁webView，防止音乐视频等还在播放
        //防止内存泄漏（加载null内容 ——移除webView——销毁——置空）
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);//因为光销毁，webView仍绑定在activity上，先从父容器移除
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    /**
     * 网页回退,退到上一个页面
     * （因为默认会直接退出浏览器）
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 全屏容器界面
     */
    class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }
}
